package de.rj.urwalking.data.survey;

import java.io.File;
import java.util.ArrayList;

import android.os.Environment;
import android.util.Log;

import de.rj.urwalking.config.Config;
import de.rj.urwalking.data.Experiment;
import de.rj.urwalking.db.ReadWritePostgreSQL;
import de.rj.urwalking.util.Util;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.Root;

@Root(name = "urw_participants_survey")
public class CreateParticipantSurvey extends Survey {

	private static final long serialVersionUID = 1L;
	private static final String TAG = Config.TAG;
	private static final boolean DEBUG = Config.DEBUG;
	@Element(name = "participantid")
	private int pid;
	private int intSurveyidInDb;
	@Element(name = "iscomplete")
	private boolean isCompleted = false;

	public CreateParticipantSurvey(ArrayList<Question> questions) {
		super(questions);
		this.setIntSurveyidInDb(Config.CREATE_PARTICIPANT_SURVEY_NR);
	}

	public boolean saveToXml(int participantId) {
		

		this.pid = participantId;
		String fn = "registrationdata-" + this.timestamp + "-" + this.pid + ".xml";
		boolean blnRes = false;
		Serializer serializer = new Persister(new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>"));
		Log.i(TAG, Experiment.class.getName() + ": Try to initialize file " + fn);
		File dirXml = new File(Environment.getExternalStorageDirectory(), Config.FOLDER_NAME);
		File xmlFile;
		if (dirXml.exists() && dirXml.canWrite()) {
			xmlFile = new File(dirXml, fn);
		} else {
			dirXml.mkdirs();
			xmlFile = new File(dirXml, fn);
		}

		if (DEBUG) {
			Log.i(TAG,
					Experiment.class.getName() + ": Location of XML file containing registration data: "
							+ xmlFile.getAbsolutePath());
		}
		try {
			serializer.write(this, xmlFile);
			if (xmlFile.exists()) {
				Log.i(TAG, Experiment.class.getName()
						+ ": Successfully stored registration data as XML file on sdcard: " + xmlFile.getAbsolutePath());
				blnRes = true;
			} else
				blnRes = false;

		} catch (Exception e) {
			Log.e(TAG, Experiment.class.getName() + ": Failed to store registration data as XML+" + " file on sdcard: "
					+ e.getMessage());

			if (xmlFile.exists()) {
				Util.deleteFile(xmlFile);
				blnRes = false;
			}

		}
		return blnRes;
	}

	public void setCompleted() {
		this.isCompleted = true;
	}

	private int getIntSurveyidInDb() {
		return intSurveyidInDb;
	}

	private void setIntSurveyidInDb(int intSurveyidInDb) {
		this.intSurveyidInDb = intSurveyidInDb;
	}

}
